package cc.ipost.ipost;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import cc.ipost.ipost.data.RequestData;
import cc.ipost.ipost.utils.AnimationFactory;
import cc.ipost.ipost.utils.AnimationFactory.FlipDirection;
import cc.ipost.ipost.utils.ScreenShot;

import com.umeng.analytics.MobclickAgent;

@SuppressLint("HandlerLeak")
public class MainActivity extends Activity {
	MyApplication ma;
	LayoutInflater li;
	ViewPager mPager;
	ViewGroup postMain;

	View newBtn;
	View addressBtn;
	View settingBtn;
	View historyBtn;
	TextView limitT;
	ProgressDialog loadingDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		this.li = LayoutInflater.from(this);
		// setContentView(R.layout.activity_main);
		/**
		 * next time I'll try to use one activity and pages to make it a roll.
		 */
		setContentView(R.layout.home);
		ma = (MyApplication) this.getApplication();
		if (ma.user == null) {
			Intent i = new Intent(this, AccountActivity.class);
			this.startActivity(i);
		} else {
			initView();
			// update info
			Intent in = getIntent();
			boolean reloadInfo = in.getBooleanExtra("reload", true);
			if (reloadInfo) {
				updateInfo();
			}

		}

	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			loadingDialog.dismiss();
			switch (msg.what) {
			case MySettings.FAIL: {
				Log.e("get user info fail", msg.toString());
				String msgs = "Something went wrong, please try again later.";
				if (msg != null && msg.obj != null) {
					msgs = msg.obj.toString();
				}
				new AlertDialog.Builder(MainActivity.this).setMessage(msgs)
						.setNegativeButton("OK", null).setCancelable(true)
						.show();
				break;
			}
			case MySettings.ERR: {
				Log.e("get user info err", msg.toString());
				new AlertDialog.Builder(MainActivity.this)
						.setMessage(msg.obj.toString())
						.setNegativeButton("OK", null).setCancelable(true)
						.show();
				break;
			}
			case MySettings.SUCCESS: {
				Log.e("get user info success", msg.toString());
				try {
					JSONObject user = ((JSONObject) msg.obj)
							.getJSONObject("user");
					MyApplication ma = (MyApplication) getApplication();
					ma.initUser(user);
					limitT.setText(ma.user.limit + ""); // attention limit is
														// integer..
				} catch (JSONException e) {
					e.printStackTrace();
				}
				System.out.println(msg.obj);
			}
			}

		}
	};

	private void updateInfo() {
		loadingDialog.show();
		RequestData rd = new RequestData(String.format(MySettings.USER,
				ma.user.ID), RequestData.GET);

		WebServiceTask wst = new WebServiceTask(rd, handler);
		wst.execute("");
	}

	private void initView() {
		loadingDialog = new ProgressDialog(this, R.style.MyProgressDialog);
		loadingDialog.setMessage(getString(R.string.wait_msg));
		limitT = (TextView) findViewById(R.id.postcard_limit);
		limitT.setText(ma.user.limit + ""); // attention limit is integer..
		this.newBtn = findViewById(R.id.home_btn_new);
		this.addressBtn = findViewById(R.id.home_btn_address);
		this.historyBtn = findViewById(R.id.home_btn_history);
		this.settingBtn = findViewById(R.id.home_btn_setting);
		this.newBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				if (ma.user != null && ma.user.limit > 0) {
					Intent in = new Intent(MainActivity.this,
							PostActivity.class);
					MainActivity.this.startActivity(in);
				} else {
					new AlertDialog.Builder(MainActivity.this)
							.setMessage(
									MainActivity.this
											.getString(R.string.limit_reach_notify))
							.setNegativeButton(
									MainActivity.this.getString(R.string.ok),
									null).setCancelable(true).show();
				}

			}
		});
		this.addressBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent in = new Intent(MainActivity.this,
						AddressListActivity.class);
				MainActivity.this.startActivity(in);
			}
		});
		this.historyBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent in = new Intent(MainActivity.this, HistoryActivity.class);
				MainActivity.this.startActivity(in);

			}
		});
		this.settingBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent in = new Intent(MainActivity.this,
						SettingsActivity.class);
				MainActivity.this.startActivity(in);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void initPager() {
		this.mPager = (ViewPager) findViewById(R.id.viewPager);
		List<View> views = new ArrayList<View>();
		views.add(this.postMain);
		views.add(li.inflate(R.layout.loading, null));
		this.mPager.setAdapter(new PostViewPagerAdapter(views));
		this.mPager.setCurrentItem(0);
	}

	public void initPostMain() {
		final ViewFlipper vf = (ViewFlipper) postMain
				.findViewById(R.id.postcard);

		vf.addView(li.inflate(R.layout.cover, null));
		vf.addView(li.inflate(R.layout.poster, null));
		View btn = postMain.findViewById(R.id.navturn_btn);
		btn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				AnimationFactory.flipTransition(vf, FlipDirection.LEFT_RIGHT);
			}
		});
		View hbtn = postMain.findViewById(R.id.navhome_btn);
		hbtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				mPager.setCurrentItem(1);
			}
		});

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			ScreenShot.shoot(this);

		}
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Toast.makeText(this, R.string.keyback_warn, Toast.LENGTH_SHORT).show();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

}
